package com.nimbusung;

import java.util.ArrayList;
import java.util.List;
import com.nimbusung.R;
import com.nimbusung.domain.ImageAdapter;
import com.nimbusung.domain.Link;
import com.nimbusung.gallery.GalleryConfig;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Gallery;
import android.widget.ProgressBar;

public class ImageAllPhotoActivity extends Activity {

	private Context context;
	private Gallery gallery;
	private ProgressBar progressBar;
	private List<String> sourceUrls;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.image_gallary_layout);
		
		this.context = this;
		this.gallery = (Gallery) findViewById(R.id.gallery);
		this.progressBar = (ProgressBar) findViewById(R.id.progressBar1);
		this.sourceUrls = new ArrayList<String>();
		
		readPhotos();
		
		//Set click listener 
		gallery.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View v, int position,
					long arg3) {
				
				getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
				
				Intent intent = new Intent(ImageAllPhotoActivity.this, ImageFullscreenActivity.class);
				intent.putExtra("imageUri", sourceUrls.get(position));
				startActivity(intent);
				
			}
		});
	}


	/**
	 * A class to download content/news asynchronously in the background
	 * @author Anton
	 */
	private class DownloadNewsPageTask extends AsyncTask<String, Void, List<String>>{

		@Override 
		protected void onPreExecute(){

		}

		@Override
		protected List<String> doInBackground(String... params) {
			
			ArrayList<String> urls = new ArrayList<String>();
			
			GalleryConfig g = new GalleryConfig();
			
			ArrayList<String> filadelfiaPhotos = g.fetchPhotos(Link.getLinks("albumNimbus"));
			ArrayList<String> nimbusPhotos = g.fetchPhotos(Link.getLinks("albumFiladelfia"));

			urls.addAll(filadelfiaPhotos);
			urls.addAll(nimbusPhotos);
			
			return urls;
		}


		@Override
		protected void onPostExecute(List<String> result){

			//Call and set the imageAdapter 
			gallery.setAdapter(new ImageAdapter(context, result));
			progressBar.setVisibility(View.INVISIBLE);
			sourceUrls = result;
		}
	}
	
	public void readPhotos(){

		DownloadNewsPageTask task = new DownloadNewsPageTask();
		task.execute(new String[] {"Download and parse photos"});
	}
}

